package com.etung.iot.demo.services.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.etung.iot.demo.configs.MqttConfig;
import com.etung.iot.demo.dao.AccessInfoMapper;
import com.etung.iot.demo.modles.AccessInfo;
import com.etung.iot.demo.services.MqttAuthService;
import com.etung.iot.demo.utils.MD5Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

@Service
@Slf4j
public class MqttAuthServiceImpl implements MqttAuthService {

    @Autowired
    private AccessInfoMapper accessInfoMapper;

    @Autowired
    private MqttConfig mqttConfig;

    @Value("${mqtt.super-client}")
    private String adminClientId;

    @Value("${mqtt.super-username}")
    private String adminUser;

    @Transactional
    @Override
    public boolean auth(String clientId, String username, String password) {
        log.info(String.format("clientid:%s,username:%s,password:%s",clientId,username, password));
        if(StringUtils.isEmpty(clientId) || StringUtils.isEmpty(username) || StringUtils.isEmpty(password)){
            return false;
        }
        if(username.equals(mqttConfig.getUsername()) && clientId.equals(mqttConfig.getClientId())) return true;
        if(username.equals(adminUser) && clientId.equals(adminClientId)) return true;
        String[] parts = clientId.split("\\|");
        if(parts.length != 2) return false;
        String productKey = parts[0];
        String deviceName = username;
        //通过productKey从数据库去取deviceSecret
        AccessInfo accessInfo = accessInfoMapper.selectOne(new QueryWrapper<AccessInfo>().eq("product_key", productKey).eq("device_name", deviceName));
        if(accessInfo == null) return false;
        String genPassword = MD5Util.stringToMD5(MD5Util.xorEncrypt(clientId + username, accessInfo.getDeviceSecret()));
        log.info(String.format("clientid:%s,username:%s,password:%s----------genPassword:%s",clientId,username,password,genPassword));
        if(!password.equalsIgnoreCase(genPassword)) return false;
        return true;
    }

    @Override
    public boolean aclAuth(String access, String username, String clientid, String ipaddr, String topic, String mountpoint) {
        return true;
    }

    @Override
    public boolean isSuperUser(String clientid, String username) {
        log.info(String.format("clientid:%s,username:%s",clientid,username));
        if(mqttConfig.getClientId().equals(clientid) && mqttConfig.getUsername().equals(username)){
            return true;
        }
        return false;
    }

}
